package com.away.ymcc.service.Impl;

import com.away.ymcc.constsant.BusinessConstants;
import com.away.ymcc.constsant.GlobleExceptionConstant;
import com.away.ymcc.dto.CodeDTO;
import com.away.ymcc.exception.GlobleException;
import com.away.ymcc.service.VerifyCodeService;
import com.away.ymcc.util.StrUtils;
import com.away.ymcc.utils.SendSmsUtil;
import com.mysql.cj.util.StringUtils;
import lombok.extern.slf4j.Slf4j;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class VerifyCodeServiceImpl implements VerifyCodeService {
   @Resource
   private RedisTemplate<Object,Object> redisTemplate;
    
    @Override
    public void sendSmsCode(String phone) {
        // TODO: 2025/7/8 发送短信验证码
        //业务逻辑实现
        //1.接收到phone,校验
        if(StringUtils.isNullOrEmpty(phone)){
            throw new GlobleException("PHONE_IS_NULL");
        }
        //2.检查是否有验证码
        //key:业务键+phone
        String key = BusinessConstants.PHONE_REGISTER + phone;
        Object obj = redisTemplate.opsForValue().get(key);
        CodeDTO value = null;
        if(obj != null){
            //2.1有验证码
            value = (CodeDTO)obj;
            //2.1.1过期时间是否超过1min 提示用户一分钟只能获取一次
            if(new Date().getTime() - value.getTimer() < 60*1000){
                throw new GlobleException("请勿重复发送验证码");
            }
            //2.2.2 1-5分钟 把获取到的验证码发送给用户 更新过期时间

        }else{
            //2.2没有直接生成生成验证码
            String code = StrUtils.getRandomString(4);

            //value:{code,timer}
            long timer = new Date().getTime();
            value = new CodeDTO(code, timer);
            // 保存到缓存过期时间5分钟 发送给用户

        }
        log.info("验证码为:{}", value.getCode());
        //SendSmsUtil.send(phone,value.getCode());
        redisTemplate.opsForValue().set(key,value,5, TimeUnit.MINUTES);

    }
}
